﻿using System;
using System.Collections.Generic;
using System.Linq;
using Bazookabird.Wpf.Model;
using Caliburn.Micro;
using Microsoft.TeamFoundation.WorkItemTracking.Client;

namespace Bazookabird.Wpf.Queries.QueryHandlers.SimpleSprintViewer
{
    public class WorkItemTimeline : PropertyChangedBase
    {
        public WorkItemTimeline(WorkItemNode workitem, DateTime startDate, DateTime endDate)
        {
            WorkItemNode = workitem;  
            var revisions = new RevisionCollection(WorkItemNode);
            Timeline = ProduceTimeline(revisions, startDate, endDate);
        }

        private Dictionary<DateTime, Revision> _timeline;
        public Dictionary<DateTime, Revision> Timeline
        {
            get { return _timeline; }
            private set
            {
                _timeline = value;
                NotifyOfPropertyChange(() => Timeline);
            }
        }

        private WorkItemNode _workItemNode;
        public WorkItemNode WorkItemNode
        {
            get { return _workItemNode; }
            private set
            {
                _workItemNode = value;
                NotifyOfPropertyChange(() => WorkItemNode);
            }
        }

        private Dictionary<DateTime, Revision> ProduceTimeline(RevisionCollection revisions, DateTime startDate, DateTime endDate)
        {
            var dictionary = new Dictionary<DateTime, Revision>();
            startDate = startDate.Date;
            endDate = endDate.Date.AddDays(1);

            for (var date = startDate; date < endDate; date = date.AddDays(1))
            {
                var revision = GetRevisionByDate(revisions, date);
                dictionary.Add(date, revision);
            }
            return dictionary;
        }
        
        private Revision GetRevisionByDate(IEnumerable<Revision> revisions, DateTime date)
        {
            if (date.Date < WorkItemNode.WorkItem.CreatedDate.Date)
            {
                return null;
            }

            var orderedItemsForDate = revisions
                .Where(r => r.Fields["System.ChangedDate"].Value.ToDateTime() <= date.Date.AddDays(1))
                .ToList();

            return orderedItemsForDate.LastOrDefault();
        }
    }

    public static class TimelineExtensions
    {
        public static DateTime ToDateTime(this object value)
        {
            return DateTime.Parse(value.ToString());
        }
    }
}
